/**
 * 用户数据模型
 * 处理用户相关的数据库操作
 */
const { pool, query } = require('../config/database');
const bcrypt = require('bcryptjs');

const userModel = {
  /**
   * 根据用户名查找用户
   * @param {string} username - 用户名
   * @returns {Promise<Object|null>} 用户对象或null
   */
  findByUsername: async (username) => {
    const sql = 'SELECT * FROM users WHERE username = ?';
    const users = await query(sql, [username]);
    return users.length ? users[0] : null;
  },

  /**
   * 根据ID查找用户
   * @param {number} id - 用户ID
   * @returns {Promise<Object|null>} 用户对象或null
   */
  findById: async (id) => {
    const sql = 'SELECT id, username, nickname, avatar, bio, created_at FROM users WHERE id = ?';
    const users = await query(sql, [id]);
    return users.length ? users[0] : null;
  },

  /**
   * 创建新用户
   * @param {Object} userData - 用户数据
   * @returns {Promise<Object>} 创建的用户
   */
  create: async (userData) => {
    // 密码加密
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(userData.password, salt);
    
    const sql = 'INSERT INTO users (username, password, nickname) VALUES (?, ?, ?)';
    const result = await query(sql, [
      userData.username,
      hashedPassword,
      userData.nickname || userData.username
    ]);
    
    return { id: result.insertId, username: userData.username };
  },

  /**
   * 更新用户信息
   * @param {number} id - 用户ID
   * @param {Object} updateData - 要更新的字段
   * @returns {Promise<boolean>} 更新是否成功
   */
  update: async (id, updateData) => {
    const allowedFields = ['nickname', 'avatar', 'bio'];
    const fields = [];
    const values = [];

    // 构建动态更新SQL
    for (const field of allowedFields) {
      if (updateData[field] !== undefined) {
        fields.push(`${field} = ?`);
        values.push(updateData[field]);
      }
    }

    if (fields.length === 0) return false;

    values.push(id);
    const sql = `UPDATE users SET ${fields.join(', ')} WHERE id = ?`;
    const result = await query(sql, values);
    
    return result.affectedRows > 0;
  }
};

module.exports = userModel; 